<?php
namespace app\index\model;

use Exception;
use think\Model;
use think\Db;
use think\Log;

class DeliveryChange extends Model{
    /**
     * 获取交期变更单列表
     */
    public function getList($page = '', $limit = '', $orderNo = '', $customerName = '', $submitName = '', $type = 1, $uid, $privilege = 0,$status = ''){
        if ($privilege) {
            $where = " a.deleted = 0 and b.deleted = 0 and c.type = $type ";
        } else {
            $where = " a.deleted = 0 and b.deleted = 0 and c.type = $type and c.uid = $uid ";
        }
        if ($orderNo) {
            $where .= " and concat_ws('',a.num, a.desc) = '".$orderNo."'";
        }
        if ($customerName) {
            $where .= " and a.cCusName = '".$customerName."'";
        }
        if ($submitName) {
            $where .= " and c.username = '".$submitName."'";
        }
        if ($status !== ''){
            $where .= " and c.status = '".$status."'";
        }
        return db('ordernum')
                ->alias('a')
                ->join('order b','a.status = b.id')
                ->join('delivery_change c', 'a.id = c.order_num_id')
                ->where($where)
                ->field('a.id, a.num, a.ddLeiXing, a.orderType, a.desc, a.zhangtao, b.currency, a.cCusName, b.date1, b.id as orderId, a.cCusPPersonText, b.atTime, c.id as delivery_id, c.delivery_date, c.status, c.is_show as isShow, c.username, c.ctime, c.type')
                ->limit(($page-1)*$limit, $limit)
                ->select();
    }

    //变更单的数量
    public function count($orderNo = '', $customerName = '', $submitName = '', $type = 1, $uid, $privilege = 0,$status = ''){
        if ($privilege) {
            $where = " a.deleted = 0 and b.deleted = 0 and c.type = $type ";
        } else {
            $where = " a.deleted = 0 and b.deleted = 0 and c.type = $type and c.uid = $uid ";
        }
        if ($orderNo) {
            $where .= " and concat_ws('',a.num, a.desc) = '".$orderNo."'";
        }
        if ($customerName) {
            $where .= " and a.cCusName = '".$customerName."'";
        }
        if ($submitName) {
            $where .= " and c.username = '".$submitName."'";
        }
        if ($status !== ''){
            $where .= " and c.status = '".$status."'";
        }
        return db('ordernum')
                ->alias('a')
                ->join('order b','a.status = b.id')
                ->join('delivery_change c', 'a.id = c.order_num_id')
                ->where($where)
                ->count();
    }

    //我的审核列表的数量
    public function myCount($orderNo = '', $customerName = '', $submitName = '', $status, $uid = ''){
        $where = " d.uid = $uid ";
        if ($orderNo) {
            $where .= " and concat_ws('',a.num, a.desc) = '".$orderNo."'";
        }
        if ($customerName) {
            $where .= " and a.cCusName = '".$customerName."'";
        }
        if ($submitName) {
            $where .= " and c.username = '".$submitName."'";
        }
        if ($status) {
            if ($status == 1) {
                $status = 0;
            }
            $where .= " and d.status = $status ";
        }
        return db('ordernum')
        ->alias('a')
        ->join('order b','a.status = b.id')
        ->join('delivery_change c', 'a.id = c.order_num_id')
        ->join('delivery_change_verify d', 'c.id = d.change_id')
        ->where($where)
        ->count();
    }

    //销售到计划
    public function saveData1($arrayList, $username, $type, $fromUid,$name){


//        foreach($arrayList as $array) {
//            $uidArray = [];
//            $orderList = db('orderlist')->where(['orderId'=>$array['orderId'], 'deleted'=>0])->select();
//            $orderList = $orderList->toArray();
//            if (!empty($orderList)) {
//                //再根据 厂区、产品属性 和 订单类型获取对应的审核人员（uids）（表 dev_factory  type = ‘计划员接收’,其他3个字段看注释）
//                foreach($orderList as $order){
//                    //print_r(['type'=>$type, 'factory'=>$order['factory'], 'complete'=>$order['complete'], 'sale_type'=>$array['ddLeiXing']]);
//                    $uidList = db('factory')->where(['type'=>$type,'name'=>$name,'factory'=>$order['factory'], 'complete'=>$order['complete'], 'sale_type'=>$array['ddLeiXing']])->field('uids,uManageUids')->select();
//
//                    $uidList = $uidList->toArray();
//                    if (!empty($uidList)) {
//                        $uidArray = array_merge($uidArray, _array_column($uidList, 'uManageUids'));
//                    }
//                }
//            }
//
////            foreach($uidArray as &$item){
////                $uid = array_filter(explode(',',$item));
////                foreach($uid as $k=>&$v){
////                    if(strpos('31,1003,735,312,509,907,952,1789,1914,10488',$v) !== false){
////                        unset($uid[$k]);
////                    }
////                }
////                $item = implode(',',$uid);
//////                    $pos = strpos($item, ',');
////                //$item = substr($item, 0, $pos);
////
////            }
//            $uids = array_unique($uidArray);
//            Log::record("RETURN ORDERLIST ".json_encode($uids));
//            //判断是不是有重复的
//            $where = [];
//            $where['order_num_id'] = $array['id'];
//            $where['order_id'] = $array['orderId'];
//            $where['type'] = 1;
//            $where['status'] = ['in', '0,1'];
//            $exist = db('delivery_change')->where($where)->find();
//            if(!empty($exist)) {
//                throw new Exception('请不要重复提交数据！！');
//            }
//            if (!empty($uids)) {
//                $data = [
//                    'order_num_id' => $array['id'],
//                    'order_id' => $array['orderId'],
//                    'delivery_date' => $array['deliveryDate'],
//                    'is_show' => $array['isShow'],
//                    'username' => $username,
//                    'uid' => $fromUid,
//                    'ctime' => time(),
//                    'mtime' => time(),
//                    'type' => 1
//                ];
//                $id = db('delivery_change')->insertGetId($data);
//                Log::record("RETURN ID ".$id);
//
//                $arr_tmp = array();
//                foreach($uids as $k=>$v){
//                    $arr = explode(',',$v);
//                    foreach($arr as $k2=>$v2){
//                        array_push($arr_tmp,$v2);
//                    }
//
//                }
//                $arr_tmp = array_filter(array_unique($arr_tmp));
//                foreach ($arr_tmp as $uid) {
//                    $para = [
//                        'change_id'=>$id,
//                        'uid'=> $uid,
//                        'ctime'=>time()
//                    ];
//                    db('delivery_change_verify')->insert($para);
//                    array_push($totalUids, $uid);
//
//                }
//            } else {
//                //没有找到审核人先跳过去
//                array_push($notFoundArray, $array['id']);
//                // throw Exception('ID: '.$array['id'].' 没有找到审核人');
//            }
//
//        }



        db('delivery_change')->startTrans();
        try{
            $notFoundArray = [];
            $totalUids = [];
            foreach($arrayList as $array) {
                $uidArray = [];
                
                $orderList = db('orderlist')->where(['orderId'=>$array['orderId'], 'deleted'=>0])->select();
                $orderList = $orderList->toArray();
                if (!empty($orderList)) {
                    //再根据 厂区、产品属性 和 订单类型获取对应的审核人员（uids）（表 dev_factory  type = ‘计划员接收’,其他3个字段看注释）
                    foreach($orderList as $order){
                        //print_r(['type'=>$type, 'factory'=>$order['factory'], 'complete'=>$order['complete'], 'sale_type'=>$array['ddLeiXing']]);
                        $uidList = db('factory')->where(['type'=>$type,'name'=>$name,'factory'=>$order['factory'], 'complete'=>$order['complete'], 'sale_type'=>$array['ddLeiXing']])->field('uids,uManageUids')->select();

                        $uidList = $uidList->toArray();
                        if (!empty($uidList)) {
                            $uidArray = array_merge($uidArray, _array_column($uidList, 'uManageUids'));
                        }
                    }
                }

//                foreach($uidArray as &$item){
//                    $uid = array_filter(explode(',',$item));
//                    foreach($uid as $k=>&$v){
//                        if(strpos('31,1003,735,312,509,907,952,1789,1914,10488',$v) !== false){
//                            unset($uid[$k]);
//                        }
//                    }
//                    $item = implode(',',$uid);
////                    $pos = strpos($item, ',');
//                    //$item = substr($item, 0, $pos);
//
//                }
                $uids = array_unique($uidArray);
                Log::record("RETURN ORDERLIST ".json_encode($uids));
                //判断是不是有重复的
                $where = [];
                $where['order_num_id'] = $array['id'];
                $where['order_id'] = $array['orderId'];
                $where['type'] = 1;
                $where['status'] = ['in', '0,1'];
                $exist = db('delivery_change')->where($where)->find();
                if(!empty($exist)) {
                    throw new Exception('请不要重复提交数据！！');
                }
                if (!empty($uids)) {
                    $data = [
                        'order_num_id' => $array['id'],
                        'order_id' => $array['orderId'],
                        'delivery_date' => $array['deliveryDate'],
                        'is_show' => $array['isShow'],
                        'username' => $username,
                        'uid' => $fromUid,
                        'ctime' => time(),
                        'mtime' => time(),
                        'type' => 1
                    ];
                    $id = db('delivery_change')->insertGetId($data);
                    Log::record("RETURN ID ".$id);

                    $arr_tmp = array();
                    foreach($uids as $k=>$v){
                        $arr = explode(',',$v);
                        foreach($arr as $k2=>$v2){
                            array_push($arr_tmp,$v2);
                        }

                    }
                    $arr_tmp = array_filter(array_unique($arr_tmp));
                    foreach ($arr_tmp as $uid) {
                        $para = [
                            'change_id'=>$id,
                            'uid'=> $uid,
                            'ctime'=>time()
                        ];
                        db('delivery_change_verify')->insert($para);
                        array_push($totalUids, $uid);

                    }
                } else {
                    //没有找到审核人先跳过去
                    array_push($notFoundArray, $array['id']);
                    // throw Exception('ID: '.$array['id'].' 没有找到审核人');
                }
                
            }
            db('delivery_change')->commit();
            $totalUids = array_unique($totalUids);
            if (!empty($totalUids)) {
                foreach($totalUids as $uid) {
                    $content = "您有新的审核流程，请去审核！";
                    $remindUrl = "1:guojigang/public/index/delivery/verifyList";
                    send_message($fromUid, $uid, $content, $remindUrl);
                }
            }
            return $notFoundArray;
        } catch (\Exception $e) {
            Log::record("RETURN ERROR ". $e->getMessage());
            // 回滚事务
            db('delivery_change')->rollback();
            throw $e;
        }
    }

    //计划到销售
    public function saveData2($arrayList, $username, $fromUid){
        db('delivery_change')->startTrans();
        try{
            $totalUids = [];
            foreach($arrayList as $array) {
                $data = [
                    'order_num_id' => $array['id'],
                    'order_id' => $array['orderId'],
                    'delivery_date' => $array['deliveryDate'],
                    'is_show' => $array['isShow'],
                    'username' => $username,
                    'uid' => $fromUid,
                    'ctime' => time(),
                    'mtime' => time(),
                    'type' => 2
                ];
                $id = db('delivery_change')->insertGetId($data);
                Log::record("RETURN ID ".$id);
                $atUserInfo = db('order')->where(['id'=>$array['orderId']])->field('atUser')->find();
                Log::record("RETURN ORDERLIST ".json_encode($atUserInfo));
                $atUser = $atUserInfo['atUser'];
                $para = [
                    'change_id'=>$id,
                    'uid'=> $atUser,
                    'ctime'=>time()
                ];
                array_push($totalUids, $atUser);
                $verifyId = db('delivery_change_verify')->insertGetId($para);
                //写入待办事项
                $this->addAgentToDo($atUser, $username, $fromUid, $array['orderId'], $verifyId);
            }
            db('delivery_change')->commit();
            $totalUids = array_unique($totalUids);
            Log::record("SEND MESSAGE, FROM_UID: ".$fromUid. "TO_UIDS：". json_encode($totalUids));
            if (!empty($totalUids)) {
                foreach($totalUids as $uid) {
                    $content = "您有新的审核流程，请去审核！";
                    $remindUrl = "1:guojigang/public/index/delivery/verifyList";
                    Log::record("SEND MESSAGE, FROM_UID: ".$fromUid. " TO_UID：". $uid);
                    send_message($fromUid, $uid, $content, $remindUrl);
                }
            }
        } catch (\Exception $e) {
            Log::record("RETURN ERROR ". $e->getMessage());
            // 回滚事务
            db('delivery_change')->rollback();
            throw $e;
        }
    }

    //加入待办事项
    public function addAgentToDo($uid, $username, $fromUid, $orderId, $verifyId){
        db('user_agency')->startTrans();    
        try {
            $orderInfo = db('order')->where(['id'=>$orderId])->find();
            $params['creator_id']= $fromUid;
            $params['beginer_id']= $fromUid;
            $params['beginer_name']= $username;
            $params['creator_name']= $username;
            $params['user_id'] = $uid;
            $params['user_name'] = $username;
            $params['flow'] = iconv('UTF-8', 'GBK', '计划批量变更');
            $params['step'] = iconv('UTF-8', 'GBK', '销售审核');
            $params['link'] = '/general/guojigang/public/index/delivery/verifyList';
            $params['form_name'] = iconv('UTF-8', 'GBK', '计划发起的订单批量变更【订单号：'.$orderInfo["orderNum"].'】');
            $params['msg'] = iconv('UTF-8', 'GBK', '有新的[计划发起的批量变更：'.$orderInfo["orderNum"].']需要您审核');
            $lastId = db('user_agency')->insertGetId($params);
            $data['mark'] = $verifyId;
            db('user_agency')->where(['id'=>$lastId])->update($data);
            db('user_agency')->commit();
            return true;
        } catch (\Exception $e) {

            Log::record("RETURN ERROR AGENT ". $e->getMessage());
            db('user_agency')->rollback();
        }            
    }

    public function updateAgentFinish($id, $uid){
        $where = ['mark'=>$id, 'user_id'=>$uid];
        $status = iconv('UTF-8', 'GBK', '办理完毕');
        return db('user_agency')->where($where)->update(['status'=>$status]);
    }

    /**
     * 所有的审核列表
     */
    public function getVerifyList($page = '', $limit = '', $orderNo = '', $customerName = '', $submitName = ''){
        $where = " a.deleted = 0 and b.deleted = 0 ";
        if ($orderNo) {
            $where .= " and concat_ws('',a.num, a.desc) = '".$orderNo."'";
        }
        if ($customerName) {
            $where .= " and a.cCusName = '".$customerName."'";
        }
        if ($submitName) {
            $where .= " and c.username = '".$submitName."'";
        }
        return db('ordernum')
                ->alias('a')
                ->join('order b','a.status = b.id')
                ->join('delivery_change c', 'a.id = c.order_num_id')
                ->where($where)
                ->field('a.id, a.num, a.ddLeiXing, a.desc, a.zhangtao, b.currency, a.cCusName, b.date1, a.cCusPPersonText, b.atTime, c.id as delivery_id, c.status, c.delivery_date, c.username, c.ctime')
                ->limit(($page-1)*$limit, $limit)
                ->select();
    }

    /**
     * 根据审核人获取审核列表
     */
    public function myVerifyList($page = '', $limit = '', $orderNo = '', $customerName = '', $submitName = '', $status, $uid = ''){
        if($uid==1){
            $where = " 1=1";
        }else{
            $where = " d.uid = $uid ";
        }

        if ($orderNo) {
            $where .= " and concat_ws('',a.num, a.desc) = '".$orderNo."'";
        }
        if ($customerName) {
            $where .= " and a.cCusName = '".$customerName."'";
        }
        if ($submitName) {
            $where .= " and c.username = '".$submitName."'";
        }
        if ($status) {
            if ($status == 1) {
                $status = 0;
            }
            $where .= " and d.status = $status ";
        }
        return db('ordernum')
                ->alias('a')
                ->join('order b','a.status = b.id')
                ->join('delivery_change c', 'a.id = c.order_num_id')
                ->join('delivery_change_verify d', 'c.id = d.change_id')
                ->where($where)
                ->field('a.id, a.num, a.ddLeiXing, a.orderType, a.desc, a.zhangtao, b.currency, a.cCusCode, a.cCusName, b.date1, b.date2, a.cCusPPersonText, b.atTime, b.id as orderId, b.is_show as oldIsShow, c.id as delivery_id, c.is_show as isShow, c.delivery_date, c.username, c.ctime, c.status as changeStatus, d.id as verify_id, d.status')
                ->limit(($page-1)*$limit, $limit)
                ->select();
    }

    /**
     * 审核自己的订单
     */
    public function doVerify($ids, $status, $uid, $uname){
        db()->startTrans();
        try{
            if (!empty($ids)) {
                foreach($ids as $id) {
                    $before = db('delivery_change_verify')->where(['id'=> $id, 'uid'=> $uid])->find();
                    if(empty($before)) {
                        throw new Exception('没有找到审核单数据');
                    }
                    $this->updateAgentFinish($id, $uid);
                    db('delivery_change_verify')->where(['id'=>$id, 'uid'=>$uid])->update(['status'=>$status, 'mtime'=>time()]);
                    $logModel = new ActionLog();
                    //交期变更
                    if ($status == 3) {
                        $before1 = db('delivery_change')->where(['id'=>$before['change_id']])->find();
                        if(empty($before1)) {
                            throw new Exception('没有找到变更单数据');
                        }
                        db('delivery_change')->where(['id'=>$before['change_id']])->update(['status'=> 3, 'mtime'=>time()]);
                        $after1 = db('delivery_change')->where(['id'=>$before['change_id']])->find();
                        //交期审核变更日志
                        $logModel->insertLog($before1, $after1, JQ_SH_BG, $uname);
                        $content = "您有订单审核没有通过！";
                        $remindUrl = "1:guojigang/public/index/delivery/verifyList";
                        $toUid = $before1['uid'];
                        send_message($uid, $toUid, $content, $remindUrl);
                    } else {
                        $this->doFinish($before['change_id'], $uname, $uid);
                    }
                }   
            }
            db()->commit();
            return true;  
        }catch(\Exception $e){
            db()->rollback();
            Log::record("ROLL BACK INFO2 : EXCEPTION: ". $e->getMessage());
            throw $e;
        }
        
    }

    /**
     * 结束所有单子
     */
    public function doFinish($changeId, $uname, $uid = 0){ 
        $finish = 1;
        $result = db('delivery_change_verify')->where(['change_id'=> $changeId])->select();
        $result = $result->toArray();
        if(empty($result)) {
            throw new Exception('没有找到对应的数据');
        } else {
            foreach($result as $item) {
                if ($item['status'] != 2) {
                    $finish = 0;
                }
            }
        }
        if ($finish) {
            $before1 = db('delivery_change')->where(['id'=>$changeId])->find();
            db('delivery_change')->where(['id'=>$changeId])->update(['status'=> 2, 'mtime'=>time()]);
            $after1 = db('delivery_change')->where(['id'=>$changeId])->find();
            $logModel = new ActionLog();
            //交期审核变更日志,变更单日志
            $logModel->insertLog($before1, $after1, JQ_SH_BG, $uname);
            //变更dev_order表
            $before2 = db('order')->where(['id'=>$after1['order_id']])->find();
            //如果变更的是关闭状态
            if (!$after1['is_show']) {
                db('order')->where(['id'=>$after1['order_id']])->update(['is_show'=>$after1['is_show']]);
            } else {
                db('order')->where(['id'=>$after1['order_id']])->update(['date2'=>$after1['delivery_date'], 'is_show'=>$after1['is_show']]);
            }
            $after2 = db('order')->where(['id'=>$after1['order_id']])->find();
            //交期审核变更日志,订单日志
            $oldData = $before2;
            $newData = $after2;
            $oldData['id'] = $before1['id'];
            $newData['id'] = $after1['id'];
            $logModel->insertLog($oldData, $newData, JQ_SH_BG, $uname);
            $logModel->insertLog($before2, $after2, JQ_DD_BG, $uname);
            $this->syncMiddleTable($after1['order_num_id'], $after1['order_id']);
            $this->sendFinishMsg($uid,$result);
        } else {
            $before1 = db('delivery_change')->where(['id'=>$changeId])->find();
            db('delivery_change')->where(['id'=>$changeId])->update(['status'=> 1, 'mtime'=>time()]);
            $after1 = db('delivery_change')->where(['id'=>$changeId])->find();
            $logModel = new ActionLog();
            //交期变更
            $logModel->insertLog($before1, $after1, JQ_SH_BG, $uname);
        }
        return $finish;
        
    }

    /**
     * 同步中间表
     */
     public function syncMiddleTable($orderNumId, $orderId){
        $config = db('config')->where(['zhangTao'=>'JX'])->find();
        if (!empty($config)) {
            $hostName = $config['ip'];
            $pass = $config['pass'];
            $uid = $config['uid'];
        } else {
            throw new Exception('配置项没有找到');
        }
        $db = 'MiddleBase';
        $dbConfig = [
            'type'            => 'sqlsrv',
            // // 服务器地址
            'hostname'        => $hostName,
            // // 数据库名
            'database'        => $db,
            // // 用户名
            'username'        => $uid,
            // // 密码Zxcv123!
            'password'        => $pass,
            // 连接dsn
            'dsn'             => 'sqlsrv:Server='.$hostName.';Database='.$db
        ];
        $conn = Db::connect($dbConfig);
        $orderNum = db('ordernum')->where(['id'=>$orderNumId])->find();
        if (empty($orderNum)) {
            throw new Exception('ordernum数据没有找到');
        }
        $order = db('order')->where(['id'=>$orderId])->find();
        if (empty($order)) {
            throw new Exception('order数据没有找到');
        }
        $orderZhangTao = $orderNum['zhangTao'];
        $ztInfo = db('config')->where(['zhangTao'=>$orderZhangTao])->find();
        if (empty($ztInfo)) {
            throw new Exception('订单对应账套数据为空');
        }
        $orderList = db('orderlist')->where(['orderId'=>$orderId, 'deleted'=>0])->select();
        if (empty($orderList)) {
            throw new Exception('orderlist数据为空');
        }
        $conn->startTrans();
        try{
            $tempArr1 = [];    
            $tempArr1['cSOCode'] =  iconv('GBK', 'UTF-8',$orderNum['num'].$orderNum['desc']);
            $tempArr1['UFAccount'] = $ztInfo["db3"];//账套号
            if ($orderNum['ddLeiXing'] == 'YW') {
                $tempArr1['cVouchType'] = '外销';
            } elseif ($orderNum['ddLeiXing'] == 'NX' || $orderNum['ddLeiXing'] == 'JJ'){
                $tempArr1['cVouchType'] = '内销';
            } else {
                $tempArr1['cVouchType'] = '';
            }
            $tempArr1['dCreateDate'] = date('Y-m-d H:i:s');
            $ret1 = $conn->table('SOMain_History')->insert($tempArr1);
            if (empty($ret1)) {
                throw new Exception('写入SOMain_History表数据失败');
            }
            $isShow = 1;
            //如果是订单关闭
            if (!$order['is_show']) {
                $isShow = 0;
            }
            foreach($orderList as $val) { 
                $tempArr2 = array();
                $tempArr2['ID'] = $orderId;//订单号
                $tempArr2['cSOCode'] = iconv('GBK', 'UTF-8',$orderNum['num'].$orderNum['desc']);
                if ($isShow) {
                    $tempArr2['dPreMoDate'] =$order['date2']; //确认交期
                    $tempArr2['dPreDate'] =$order['date2']; //确认交期
                }
                $tempArr2['oaautoid'] = $val['id']; //list表id
                $tempArr2['cInvCode'] = $val['u8Code'];//存货编码
                if (!$isShow) {
                    $tempArr2['iQuantity'] = 0;//关闭
                }
                $tempArr2['bdelete'] = 0;//删除标识
                $tempArr2['iState'] = 0; //默认：0
                $ret2 = $conn->table('SODetails_History')->insert($tempArr2);
                if (empty($ret2)) {
                    throw new Exception('写入SODetails_History表数据失败');
                }
            }
            $conn->commit();
        }catch(\Exception $e){
            Log::record("ROLL BACK INFO1 : EXCEPTION: ". $e->getMessage());
            $conn->rollback();
            throw $e;
        }
        return true;  
     }

    /**
     * 订单下面的审核流程
     */
    public function nodeList($id){
        $list = db('delivery_change_verify')->where(['change_id'=> $id])->select();
        return $list;
    }

    /**
     * 处理消息接收时间
     */
    public function doReceiveTime($uid){
        $info = db('delivery_change_verify')->where('uid', '=', $uid)->where('rtime', 'null')->find();
        if(!empty($info)) {
            db('delivery_change_verify')->where('uid', '=', $uid)->where('rtime', 'null')->update(['rtime'=>time()]);
        }
        return true;  
    }
    /**
     * 查询订单是否在变更中
     */
    public function checkOrderChange($orderId, $type = 1){
        return db('delivery_change')->where('order_id', '=', $orderId)->where('type', '=', $type)->where('status', 'in', '0,1')->find();
    }

    /**
     * 查找所有的审核员
     */
    public function getAllVerifyName($orderId, $type = 1){
        $where = " a.order_id = $orderId and a.type = $type ";
        $result = db('delivery_change')
                ->alias('a')
                ->join('delivery_change_verify b','a.id = b.change_id')
                ->where($where)
                ->field('b.uid')
                ->select();
        return $result;
    }

    public function findVerifyById($id){
        return db('delivery_change_verify')->where(['id'=>$id])->find();
    }

    /**
     * 更改审核员
     */
    public function modifyVerifer($id, $uname1, $uname2){
        $userInfo = Db::table('user')->where(['USER_NAME'=>$uname1])->find();
        if (empty($userInfo)) {
            throw new Exception('没有找到用户数据');
        }
        $before = db('delivery_change_verify')->where(['id'=>$id])->find();
        if (empty($before)) {
            throw new Exception('没有找到变更数据');
        }
        db('delivery_change_verify')->where(['id'=>$id])->update(['uid'=>$userInfo['UID'], 'mtime'=>time()]);
        $after = db('delivery_change_verify')->where(['id'=>$id])->find();
        $logModel = new ActionLog();
        $logModel->insertLog($before, $after, JQ_SHY_BG, $uname2);
        return true;
    }

    public function sendFinishMsg($fromUid, $result){
        if(empty($fromUid) || empty($result)){
            return false;
        }
        foreach($result as $item){
            $content = "订单审核已经完成！";
            $remindUrl = "1:guojigang/public/index/delivery/verifyList";
            send_message($fromUid, $item["uid"], $content, $remindUrl);
        }
        return true;
    }


}
?>